#include "stdafx.h"
#include "Triangle.h"
#include "Globals.h"

Matrix maScale;
Matrix maRot;
Matrix maTran;
Triangle::Triangle()
{
	m_maWorld.SetIdentity ();

	ScaleX = 1.0f;
	ScaleY = 1.0f;
	ScaleX = 1.0f;

	RotX = 0.0f;
	RotY = 0.0f;
	RotZ = 0.0f;

	Translate = Vector3();
}

void Triangle::SetPosition(Vector3 p1, Vector3 p2, Vector3 p3)
{
	m_arrVertexData[0].pos.x = p1.x;	m_arrVertexData[0].pos.y = p1.y;	m_arrVertexData[0].pos.z = p1.z;
	m_arrVertexData[1].pos.x = p2.x;	m_arrVertexData[1].pos.y = p2.y;	m_arrVertexData[1].pos.z = p2.z;
	m_arrVertexData[2].pos.x = p3.x;	m_arrVertexData[2].pos.y = p3.y;	m_arrVertexData[2].pos.z = p3.z;
}

void Triangle::SetColor(Vector4 c1, Vector4 c2, Vector4 c3)
{
	m_arrVertexData[0].col.x = c1.x; m_arrVertexData[0].col.y = c1.y; m_arrVertexData[0].col.z = c1.z; m_arrVertexData[0].col.w = 1.0f;
	m_arrVertexData[1].col.x = c2.x; m_arrVertexData[1].col.y = c2.y; m_arrVertexData[1].col.z = c2.z; m_arrVertexData[1].col.w = 1.0f;
	m_arrVertexData[2].col.x = c3.x; m_arrVertexData[2].col.y = c3.y; m_arrVertexData[2].col.z = c3.z; m_arrVertexData[2].col.w = 1.0f;
}

void Triangle::Init()
{
	glGenBuffers(1, &m_uivboId);
	glBindBuffer(GL_ARRAY_BUFFER, m_uivboId);
	glBufferData(GL_ARRAY_BUFFER, sizeof(m_arrVertexData), m_arrVertexData, GL_STATIC_DRAW);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
}

void Triangle::Update(ESContext *esConext, GLfloat deltaTime)
{
	maScale.SetScale(ScaleX, ScaleY, ScaleZ);

	Matrix maRotX, maRotY, maRotZ;
	maRotX.SetRotationX(RotX);
	maRotY.SetRotationY(RotY);
	maRotZ.SetRotationZ(RotZ);
	maRot = maRotZ * maRotX * maRotY;

	maTran.SetTranslation(Translate);

	m_maWorld = maScale * maRot * maTran;
}

void Triangle::Draw(ESContext *esContext, Shaders *myShaders)
{
	glBindBuffer(GL_ARRAY_BUFFER, m_uivboId);
	if(myShaders->positionAttribute != -1)
	{
		glEnableVertexAttribArray(myShaders->positionAttribute);
		glVertexAttribPointer(myShaders->positionAttribute, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0);
	}
	if(myShaders->colorAttribute != -1)
	{
		glEnableVertexAttribArray(myShaders->colorAttribute);
		glVertexAttribPointer(myShaders->colorAttribute, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (char*)0 + sizeof(Vector3));
	}

	Matrix maView = Globals::mainCamera->GetViewMatrix();

	if(myShaders->mvpUniform != -1)
	{
		glUniformMatrix4fv(myShaders->mvpUniform, 1, GL_FALSE, (GLfloat*)&(m_maWorld * maView * BaseCamera::Projection).m[0][0]);
	}
	
	glDrawArrays(GL_TRIANGLES, 0, 3);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
}

void Triangle::CleanUp()
{
	glDeleteBuffers(1, &m_uivboId);
}